package com.zlp.partice.io;

import org.junit.Test;

import java.io.*;
import java.net.InetAddress;
import java.net.ServerSocket;
import java.net.Socket;

/**
 * @author: zhulaiping
 * @time: 2022/8/3 10:37
 */
public class TCPDemo1 {
    //客户端，发信息到服务端
    @Test
    public void client() throws IOException {
        InetAddress byName = InetAddress.getByName("127.0.0.1");
        Socket socket = new Socket(byName,8899);
        OutputStream outputStream = socket.getOutputStream();
        outputStream.write("我是客户端".getBytes());
        //阻塞式IO,输出流必须关闭，服务端才能正常接收数据
        outputStream.close();
        socket.close();
    }

    //服务端接受信息
    @Test
    public void server() throws IOException {
        ServerSocket serverSocket = new ServerSocket(8899);
        while (true){
            Socket accept = serverSocket.accept();
            int q = 1/0;
            InputStream inputStream = accept.getInputStream();
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            byte[] buffer = new byte[1024];
            int len = 0;
            while ((len=inputStream.read(buffer))!=-1){
                baos.write(buffer,0,len);
            }
            System.out.println(new String(baos.toByteArray()));
        }
    }


    /*
    * // TODO: 2022/8/4 :
    *       1. 客户端发送数据若无结束符，服务端将会一直阻塞等待，直至读取到结束符，
    *       2. IO流的关闭也会导连接的断开
    *       3. 若想结束写入或读取，却不想关闭连接，可使用shutdownOutput
    *
     * */
    @Test
    public void client1() throws IOException {
        InetAddress byName = InetAddress.getByName("127.0.0.1");
        Socket socket = new Socket(byName,8899);
        socket.getOutputStream().write("我是客户端".getBytes());
        socket.shutdownOutput();
        //流关闭连接就直接断开了，下面获取输入流的代码就会报错,
        //socket.getOutputStream().close();
        InputStream inputStream = socket.getInputStream();
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        byte[] buffer = new byte[1024];
        int len = 0;
        while ((len=inputStream.read(buffer))!=-1){
            baos.write(buffer,0,len);
        }
        System.out.println(new String(baos.toByteArray()));
        socket.close();
    }

    //服务端接受信息
    @Test
    public void server1() throws IOException {
        ServerSocket serverSocket = new ServerSocket(8899);
        while (true){
            Socket accept = serverSocket.accept();
            InputStream inputStream = accept.getInputStream();
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            byte[] buffer = new byte[1024];
            int len = 0;
            while ((len=inputStream.read(buffer))!=-1){
                baos.write(buffer,0,len);
            }
            System.out.println(new String(baos.toByteArray()));
            accept.getOutputStream().write("拿到了数据".getBytes());
            //accept.close();
        }
    }

}
